var app = getApp()
var IP = app.globalData.IP
var dataformat = require('../../utils/dataformat')

var QQMapWX = require("../../utils/qqmap-wx-jssdk.min");
var qqmapsdk;

Page({
  /**
   * 页面的初始数据
   */

  data: {

    promiselist: [],
    timer: {},

    orderlist: [],
    //服务信息
    servicelist: [],
    employeeid: wx.getStorageSync('employeeid'),

    latitudelist: [],
    longitudelist: [],

    distancelist: [],

    currentlat: '',
    currentlng: '',


  },


  onLoad() {

    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'A4XBZ-K76R4-ENNU6-FEXPT-AGUN2-N5BGO'
    });
    //获取待接订单
    this.getorderlistbystatus(1)



  },



  //循环获取所有订单经纬度
  async getzuobiaolist() {

    var list = this.data.orderlist
    for (var i = 0; i < list.length; i++) {

      await new Promise((resolve, reject) => {
        // console.log(list[i].serviceaddress)
        //获取单个地址坐标
        qqmapsdk.geocoder({
          //获取表单传入地址
          address: list[i].serviceaddress, //地址参数
          success: res => { //成功后的回调
            var res = res.result;
            console.log(res);
            var latitude = res.location.lat;
            var longitude = res.location.lng;
            console.log(latitude)
            console.log(longitude)
            this.setData({
              latitudelist: this.data.latitudelist.concat(latitude),
              longitudelist: this.data.longitudelist.concat(longitude)
            })
            // console.log(this.data.latitudelist)
          }
        })
        resolve()
      })

    }

  },


  //计算两点距离
  getdistancelist() {
    var list = this.data.orderlist
    wx.getLocation({
      success: res => {
        this.setData({
          currentlng: res.longitude,
          currentlat: res.latitude
        });

        for (var i = 0; i < list.length; i++) {
          let s = new Promise((resolve, reject) => {

            qqmapsdk.calculateDistance({
              //from为空默认当前位置
              from: {
                latitude: this.data.currentlat,
                longitude: this.data.currentlng
              },
              //终点坐标
              to: [{
                latitude: this.data.latitudelist[i],
                longitude: this.data.longitudelist[i]
              }],
              success: res => {
                var res = res.result;
                //两点距离
                var dis = res.elements[0].distance
                console.log(dis)
                resolve(dis)
              },
            })
          })

          this.data.promiselist.push(s)


          this.setData({
            promiselist: this.data.promiselist
          })
        }

        const timer = setTimeout(() => {
          //获取promise数组存储的数据
          this.data.distancelist.length = this.data.promiselist.length;
          for (let j = 0; j < this.data.promiselist.length; j++) {
            this.data.promiselist[j].then(res => {
              this.data.distancelist[j] = res;
              this.setData({
                distancelist: this.data.distancelist,
              });
            })
          }
        }, 1000)
        this.setData({
          timer: timer
        });
        // Promise.all(this.data.promiselist).then()

      }
    })









  },


  //同步请求获取对应服务图片
  async getserviceImage() {
    this.setData({
      servicelist: []
    })
    var list = this.data.orderlist
    for (var i = 0; i < list.length; i++) {
      await new Promise((resolve, reject) => {
        wx.request({
          url: `http://${IP}:8080/service/getservicebyserviceid/` + list[i].serviceid,
          success: res => {
            this.setData({
              servicelist: this.data.servicelist.concat(res.data),
            })
            resolve();
          }
        })

      })

    }
    // console.log('servicelist')
    // console.log(this.data.servicelist)
  },
  //接单
  receiveorder(e) {
    wx.showModal({
      title: '',
      content: '确认接收此订单？',
      complete: (res) => {
        if (res.cancel) {}
        if (res.confirm) {
          wx.request({
            url: `http://${IP}:8080/order/receiveorder`,
            data: {
              employeeid: this.data.employeeid,
              id: e.currentTarget.dataset.id
            },
            success: res => {
              wx.showToast({
                title: '接单成功',
                success: res => {
                  this.onLoad()
                }
              })
            }
          })

        }
      }
    })


  },

  //获取不同状态订单 statu=1未接单 2待上门  3待评价 4已完成 5 已取消
  getorderlistbystatus(status) {

    wx.request({
      url: `http://${IP}:8080/order/getorderlistbystatus/` + status,
      success: res => {
        this.setData({
          orderlist: res.data
        })


        // 格式化时间
        this.data.orderlist.forEach((item) => {

          item.ordertime = dataformat.formatTime(item.ordertime, 'YY-MM-DD hh-mm')
        })
        this.setData({
          orderlist: this.data.orderlist
        })
        // console.log("orderlist:")
        // console.log(this.data.orderlist)

        // console.log(this.data.orderlist)
        //根据获取的id依次同步请求获取服务图片
        this.getserviceImage()
        this.getzuobiaolist()


        const timer = setTimeout(() => {
          this.getdistancelist()
        }, 300)
        this.setData({
          timer: timer
        });

      }
    })


  },








  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {


  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})